package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.FactoryArea;
import com.tbl.modules.wms.service.baseinfo.FactoryAreaService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  厂区控制层
 * @author 70486
 */
@Controller
@RequestMapping(value = "/factoryArea")
public class FactoryAreaController extends AbstractController {

    /**
     * 厂区信息
     */
    @Autowired
    private FactoryAreaService factoryAreaService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * wms调用入口
     */
    @Autowired
    private WmsService wmsService;

    /**
     * 跳转到厂区信息
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/factoryarea/factoryarea_list");
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.factoryArea));
        return mv;
    }

    /**
     * 获取厂区信息列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(2);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = factoryAreaService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 导出厂区信息Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        try {
            String sheetName = "厂区" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");


            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");
            Map<String, String> mapFields = new LinkedHashMap<>();
            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("code", "厂区编码");
                mapFields.put("name", "厂区名称");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "厂区编码");
                    } else if ("3".equals(s)) {
                        mapFields.put("name", "厂区名称");
                    }
                }
            }
            DeriveExcel.exportExcel(sheetName, factoryAreaService.getExcelList(request.getParameter("ids"), request.getParameter("queryName"),
                    request.getParameter("queryCode"), null), mapFields, response, "");
            logService.logInsert("厂区导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取厂区列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getFactoryList")
    @ResponseBody
    public Map<String, Object> getFactoryList(String queryString, int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //okk
        map.put("factoryCodeList", getSessionUser().getFactoryCode()!=null?Arrays.asList(getSessionUser().getFactoryCode().split(",")):null);
        //获取厂区列表信息 ：下拉框
        map.put("result", factoryAreaService.getFactoryList(map));
        return map;
    }

    /**
     * 弹出到厂区编辑页面
     * @param id 厂区主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toEdit.do")
    @ResponseBody
    public ModelAndView toEdit(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/factoryarea/factoryarea_edit");
        mv.addObject("edit", id != null && id != Constant.LONG_ZERO ? Constant.INT_ONE : Constant.INT_ZERO);
        mv.addObject("factoryArea", factoryAreaService.selectById(id));
        return mv;
    }

    /**
     * 保存厂区编辑名称
     * @param factory 厂区
     * @return boolean 成功/失败
     */
    @RequestMapping(value = "/saveFactory")
    @ResponseBody
    public boolean saveFactory(FactoryArea factory) {
        return factoryAreaService.updateById(factory);
    }

    /**
     * 同步厂区基础数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/synchronousdata.do")
    @ResponseBody
    public Map<String,Object> synchronousdata() {
    	try {
			logger.info(DateUtils.getTime()+" >>同步厂区基础数据....");
            Map<String, Object> xmlMap = new HashMap<>(1);
			xmlMap.put("line", new HashMap<String, Object>(2) {{
			    put("plantno", "");
			    put("plantname", "");
			}});
			wmsService.FEWMS012(xmlMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return new HashMap<String,Object>(2) {{
            put("result", true);
            put("msg", "更新成功！");
        }};
    }

}
